/*
 * 测肤数据模块
 * @Author: ljb
 * @Date: 2018-04-11 18:02:05
 * @Last Modified by: kanglin
 * @Last Modified time: 2018-07-02 15:52:14
 */
import axios from 'axios';
import qs from 'qs';

import API_LIST from 'src/API_LIST';

// import Vue from 'vue';
import Toast from 'cube-ui/lib/toast';

const record_detail = JSON.parse(sessionStorage.getItem('record_detail'));

export default {
	namespaced: true,
	state: {

		record_lists: null,

		record_detail,

	},
	mutations: {
		/* eslint-disable no-param-reassign */
		setSkinRecords(state, records) {
			state.record_lists = records;
		},
		setSkinRecordDetail(state, record) {
			state.record_detail = record;

			sessionStorage.setItem('record_detail', JSON.stringify(record));
		},

	},
	actions: {

		// 获取皮肤报告列表
		fetchSkinRecords({ commit }, {
			openid, appid, customer_id, store_id,
		}) {
			const param = {

				openid: openid || sessionStorage.getItem('user_openid'),

				appid: appid || sessionStorage.getItem('appid'),

				customer_id: customer_id || '',

				store_id: store_id || '',

			};

			const query_str = qs.stringify(param);

			return axios.get(`${API_LIST.SKIN_RECORD}?${query_str}`)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					commit('setSkinRecords', data.skin_records);
				})
				.catch((err) => {
					const toast = Toast.$create({
						type: 'error',
						time: 2000,
						txt: err.message || err.statusText,
					});
					toast.show();
				});
		},

		// 获取报告详情
		fetchSkinRecordDetail({ commit }, { openid, appid, id }) {
			const param = {

				openid: openid || sessionStorage.getItem('user_openid'),

				appid: appid || sessionStorage.getItem('appid'),

			};

			const query_str = qs.stringify(param);

			return axios.get(`${API_LIST.SKIN_RECORD}/${id}?${query_str}`)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					commit('setSkinRecordDetail', data.skin_record);

					return true;
				})
				.catch((err) => {
					const toast = Toast.$create({
						type: 'error',
						time: 2000,
						txt: err.message || err.statusText || '网络异常',
					});
					toast.show();
				});
		},

	},
	getters: {

		getSkinRecords: state => state.record_lists || [],

		getSkinRecordDetail: state => state.record_detail,

	},
};
